<?php
declare(strict_types=1);

class PhysicalStoreModel extends BaseModel
{
    protected $table = 'yf_physical_store';

    protected $principal = 'id';

    const STATUS = [
        'open' => 1
    ];

    /**
     * 分类
     */
    private const CAT_TEXT = [
        '中国移动营业厅',
        '苹果授权体验店',
        '小米授权体验店',
        '华为授权体验店'
    ];

    /**
     * @return string[]
     */
    public function getCatText(){
        return self::CAT_TEXT;
    }

    /**
     * @param $val
     * @return bool
     */
    public function hasCatText(string $val) :bool{
        return in_array($val, self::CAT_TEXT);
    }

    /**
     *按分类获取并根据经纬度计算距离排序
     *
     * @param string $cat_text
     * @param int $page
     * @param int $pagesize
     * @param float $longitude
     * @param float $latitude
     * @return array
     */
    public function findListByCategoryOrderDistance(string $cat_text, int $page, int $pagesize, float $longitude, float $latitude)
    {
        $sql = "select *,ROUND(6378.138 * 2 * ASIN( SQRT( POW( SIN( ( :latitude * PI() / 180 - latitude * PI() / 180 ) / 2 ), 2 ) + COS(:latitude * PI() / 180) * COS(latitude * PI() / 180) * POW( SIN( ( :longitude * PI() / 180 - longitude * PI() / 180 ) / 2 ), 2 ) ) ) * 1000 ) AS distance 
from {$this->table} 
where cat_text=:cat_text and status=:status 
order by distance asc 
limit :incept,:pagesize";

        $lists = $this->db->query($sql, [
                ':latitude' => $latitude,
                ':longitude' => $longitude,
                ':cat_text' => $cat_text,
                ':status' => self::STATUS['open'],
                ':incept' => ($page - 1) * $pagesize,
                ':pagesize' => $pagesize
            ])->fetchAll(PDO::FETCH_ASSOC) ?? [];

        if ($lists) {
            foreach ($lists as &$list) {
                $list['business_hours'] =  $list['cat_text'] == "中国移动营业厅" ? "8:30-18:00" : "10:00-22:00";
            }
        }

       return $lists;
    }

    /**
     * 根据分类获取列表
     *
     * @param string $cat
     * @param int $page
     * @param int $pagesize
     * @return array
     */
    public function findListByCat(string $cat, int $page, int $pagesize = 20) :array
    {
        return $this->findList(where:[
            'cat_text' => $cat
            ],colums:['title', 'address'],page:$page, pagesize: $pagesize) ?? [];
    }

}